package gemini.castor.ui.client.page;

import gemini.basic.model.Cart;
import gemini.basic.model.MonthlyPoint;
import gemini.basic.model.Order;
import gemini.basic.model.Payment;
import gemini.basic.model.User;
import gemini.castor.ui.client.ServiceCatalog;
import gemini.castor.ui.client.mvp.callback.AbstractAsyncCallback;
import gemini.castor.ui.client.mvp.event.ContainerRequestEvent;
import gemini.castor.ui.client.mvp.event.WidgetChangeEvent;
import gemini.castor.ui.client.mvp.event.WidgetChangeHandler;
import gemini.castor.ui.client.mvp.gin.CastorGinjector;
import gemini.castor.ui.client.mvp.single.CastorWidgetPresenter;
import gemini.castor.ui.client.page.content.store.shoppingcart.ShoppingCartEvent;
import gemini.castor.ui.client.page.content.store.shoppingcart.ShoppingCartHandler;
import gemini.castor.ui.client.page.content.store.shoppingcart.ShoppingCartItem;
import gemini.castor.ui.client.page.context.shoppingcartpreview.ShoppingCartPreviewItem;
import gemini.castor.ui.client.page.context.shoppingcartpreview.ShoppingCartPreviewObject;
import gemini.castor.ui.client.page.context.shoppingcartpreview.ShoppingCartPreviewWidget;
import gemini.castor.ui.client.page.menu.MenuEvent;
import gemini.castor.ui.client.page.menu.MenuHandler;
import gemini.castor.ui.client.page.menu.MenuWidget;
import gemini.castor.ui.client.page.navigation.NavigationEvent;
import gemini.castor.ui.client.page.navigation.NavigationWidget;
import gemini.castor.ui.client.page.navigation.loginwidget.LoginEvent;
import gemini.castor.ui.client.page.navigation.loginwidget.LoginFormWidget;
import gemini.castor.ui.client.page.navigation.loginwidget.LoginHandler;
import gemini.castor.ui.client.page.navigation.loginwidget.LoginInfoWidget;
import gemini.castor.ui.client.page.widget.adv.AdvWidget;
import gemini.castor.ui.client.page.widget.banner.BannerWidget;
import gemini.castor.ui.client.page.widget.information.WelcomeAccountWidget;
import gemini.castor.ui.client.page.widget.information.WelcomeCustomerWidget;
import gemini.castor.ui.client.page.widget.information.WelcomeHomeWidget;
import gemini.castor.ui.client.page.widget.information.WelcomeOfficeWidget;
import gemini.castor.ui.client.page.widget.information.WelcomeStoreWidget;
import gemini.castor.ui.client.page.widget.information.WelcomeTrainningWidget;
import gemini.castor.ui.client.page.widget.localebox.LocaleBoxWidget;
import gemini.castor.ui.client.utils.GuiUtils;
import gemini.castor.ui.client.utils.PlaceConstants;
import gemini.castor.ui.client.utils.PlaceConstants.LayoutPosition;
import gemini.castor.ui.client.utils.PlaceConstants.MenuItem;
import gemini.castor.ui.client.utils.PlaceConstants.NavigationItem;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import ch.elca.gwt.mvp.client.EventBus;
import ch.elca.gwt.mvp.client.place.Place;
import ch.elca.gwt.mvp.client.widget.WidgetDisplay;
import ch.elca.gwt.mvp.client.widget.WidgetPresenter;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;

public class RootPresenter extends CastorWidgetPresenter<RootPresenter.Display> {

    public interface Display extends WidgetDisplay {
        
    	// NOTE:  no need to understand implementation of below methods
    	// just need to know how to use
    	// read comments
    	
    	// - clear all widget in position, then add w :    w, position,   -1, false
    	// - remove widget at idx                     : null, position,  idx, true
    	// - replace widget at idx                    :    w, position,  idx, true
    	// - add widget before idx                    :    w, position,  idx, false
    	void setWidgetAtIndex(Widget w, LayoutPosition position, int idx, boolean isReplace);
    	
    	// - replace widget at last                   :    w, position,  true
    	// - add widget at last                       :    w, position, false
    	void setWidgetAtFirst(Widget w, LayoutPosition position, boolean isReplace);
    	
    	// - replace widget at first                  :    w, position,  true
    	// - add widget at first                      :    w, position, false
    	void setWidgetAtLast(Widget w, LayoutPosition position, boolean isReplace);
    	
    	int getWidgetCount(LayoutPosition position);

		String getTextTryAlso();

		String getTextRecognition();

		String getTextPromotion();

		void visibleContent(boolean b);
    }

	public static final Place PLACE = new Place(PlaceConstants.PLACE_ROOT);

	@Inject
	public RootPresenter(final Display display, final EventBus eventBus) {
		super(display, eventBus);
	}

    /*
     * Register listeners on Display actions
     */
    @Override
    protected void onBind() {
		registerHandler(eventBus.addHandler(WidgetChangeEvent.getType(),
				new WidgetChangeHandler() {
					public void onChange(
							final WidgetChangeEvent event) {
						LayoutPosition p = event.getPosition();
						if(p == null){
							p = LayoutPosition.CONTENT;
						}
						setWidgetPresenter(event.getWidgetPresenter(), p);
					}
				}));
		
		// must put initCustom method in the last, when all handler has registered
		initCustom();
    }
    
    private AdvWidget wgdRecognitions;
    
    private AdvWidget getWgdRecognitions() {
    	if (wgdRecognitions == null) {
    		wgdRecognitions = new AdvWidget();
    		
    		HorizontalPanel recognitionContent1 = new HorizontalPanel();
			Image img0 = new Image("images/logo/worldteam_icon_98x98.gif");
			img0.setStyleName("gwt-Image-tiny");
			recognitionContent1.add(img0);
			
			HTML htmPro0 = new HTML();
			htmPro0.setHTML("<b>Active world team</b>");
			htmPro0.setStyleName("productLink");
			htmPro0.setWidth("100%");
			recognitionContent1.add(htmPro0);
			
			HorizontalPanel recognitionContent2 = new HorizontalPanel();
			Image img1 = new Image("images/logo/presteam_icon_98x98.gif");
			img1.setStyleName("gwt-Image-tiny");
			recognitionContent2.add(img1);
			
			HTML htmPro1 = new HTML();
			htmPro1.setHTML("<b>President's team</b>");
			htmPro1.setStyleName("productLink");
			recognitionContent2.add(htmPro1);
			
			HorizontalPanel recognitionContent3 = new HorizontalPanel();
			Image img2 = new Image("images/logo/herbalife_98x98.jpg");
			img2.setStyleName("gwt-Image-tiny");
			recognitionContent3.add(img2);
			
			HTML htmPro2 = new HTML();
			htmPro2.setHTML("<b>Recognition certificates</b>");
			htmPro2.setStyleName("productLink");
			recognitionContent3.add(htmPro2);
			
			VerticalPanel vplContent = new VerticalPanel();
			vplContent.add(recognitionContent1);
			vplContent.add(recognitionContent2);
			vplContent.add(recognitionContent3);
			vplContent.setSpacing(5);
			
			
			wgdRecognitions.loadData(vplContent, display.getTextRecognition() );
		}
    	
    	return wgdRecognitions;
    }
    
    private AdvWidget wgdPromotion;
    
    private AdvWidget getWgdPromotion(){
    	if (wgdPromotion == null) {
    		wgdPromotion = new AdvWidget();
    		
    		
    		VerticalPanel promotionContent = new VerticalPanel();
    		Image img = new Image("images/logo/eventsModule.jpg");
    		img.setStyleName("img-Promotion");
    		promotionContent.add(img);
    		
    		HTML htmPro2 = new HTML();
    		htmPro2.setHTML("<center><b>Click for detail</b></center>");
    		htmPro2.setStyleName("productLink");
    		promotionContent.add(htmPro2);
    		
    		wgdPromotion.loadData(promotionContent, display.getTextPromotion() );
    	}
    	
    	return wgdPromotion;
	}
    
    private MenuWidget menu;
    
    private LocaleBoxWidget createLocaleBox(){
    	LocaleBoxWidget localeBox = new LocaleBoxWidget();
    	return localeBox;
    }
    
    private BannerWidget createBannerWidget(){
    	BannerWidget banner = new BannerWidget();
    	return banner;
    }
    
    private void initCustom(){
    	
    	registerHandlers();
    	
    	display.setWidgetAtFirst(createBannerWidget(), LayoutPosition.HEADER, false);
    	display.setWidgetAtLast(createLocaleBox(), LayoutPosition.HEADER, false);
    	
		display.setWidgetAtIndex(menu, PlaceConstants.LayoutPosition.MENU,
				-1, false);

		loadHomeContext();
		
		display.setWidgetAtFirst(getLoginFormWidget(), LayoutPosition.NAVIGATION, false);

		Window.alert(GWT.getModuleBaseURL() + "fileread");
		
		currentScreen();
    }
    
    public void currentScreen(){
    	getMenu().fireCurrentButtonEvent();
    }
    
    private LoginFormWidget loginFormWidget;
    
    private LoginInfoWidget loginInforWidget;
    
	private void loadHomeContext() {
		if(cartPreview!=null && !cartPreview.isClosed()){
			cartPreview.setClosed(true);
		}
		display.setWidgetAtIndex(getWgdRecognitions(), LayoutPosition.CONTEXT, -1, false);
		display.setWidgetAtLast(getWgdPromotion(), LayoutPosition.CONTEXT,
				false);
	}
	
	private LoginHandler createLoginHandler(){
		LoginHandler result = new LoginHandler() {
			
			@Override
			public void onSuccess(LoginEvent userLoginEvent) {
				getLoginInforWidget().loadData(userLoginEvent.getLoggedInUser());
				display.setWidgetAtFirst(getLoginInforWidget(), LayoutPosition.NAVIGATION, true);
				user = userLoginEvent.getLoggedInUser();
				menu.fireCurrentButtonEvent();
			}
			
			@Override
			public void onLogout(LoginEvent userLoginEvent) {
				display.setWidgetAtFirst(getLoginFormWidget(), LayoutPosition.NAVIGATION, true);
				user = null;
				menu.fireCurrentButtonEvent();
			}
		};
		return result;
	}
	private void registerHandlers() {
		
		registerHandler(getLoginFormWidget().addLoginFormHandler(createLoginHandler()));
		registerHandler(getLoginInforWidget().addLoginFormHandler(createLoginHandler()));
		
		registerHandler(eventBus.addHandler(RootEvent.getType(), new RootHandler() {
			
			@Override
			public void onUnMask(RootEvent event) {
				unmask();
			}
			
			@Override
			public void onMask(RootEvent event) {
				mask();
			}
		}));
    	registerHandler(eventBus.addHandler(ShoppingCartEvent.getType(), new ShoppingCartHandler() {
			
			@Override
			public void onCheckOut(ShoppingCartEvent event) {
				checkOutCart(event.getPaymentType(), event.getPaymentValue());
			}
			
			@Override
			public void onAdd(ShoppingCartEvent event) {
				addToCart(event.getItems());
			}

			@Override
			public void onRemove(ShoppingCartEvent event) {
				removeFromCart(event.getItems());
			}

			@Override
			public void onUpdate(ShoppingCartEvent event) {
				updateToCart(event.getItems());
			}

			@Override
			public void onViewProduct(ShoppingCartEvent event) {
				
				eventBus.fireEvent(new ContainerRequestEvent(
								CastorGinjector.INSTANCE
										.getProductCatalogPresenter()
										.getPlace().getId(), event.getProduct()));
				
				NavigationEvent navEvent = new NavigationEvent(NavigationItem.PRODUCT_CATALOG);
				navEvent.setForwardType(NavigationEvent.ForwardType.SELECTED);
				eventBus.fireEvent(navEvent);
			}
		}));
    	
    	registerHandler(getMenu().addSelectedHandler(new MenuHandler() {
			
			@Override
			public void onSelected(MenuEvent menuEvent) {
				NavigationWidget navWidget = new NavigationWidget(menuEvent.getMenuItem(), user);
				
				boolean isExistNavigation = false;
				if(display.getWidgetCount(LayoutPosition.NAVIGATION) > 1){
					isExistNavigation = true;
				}
				
				display.setWidgetAtLast(navWidget, LayoutPosition.NAVIGATION, isExistNavigation);
				
				if (menuEvent.getMenuItem().equals(MenuItem.STORE)) {
					display.setWidgetAtIndex(new WelcomeStoreWidget(), PlaceConstants.LayoutPosition.CONTENT, -1, false);
					
					if(user != null){
						loadCart();
						
					}
				} else {
					loadHomeContext();
					
					if(menuEvent.getMenuItem().equals(MenuItem.HOME)){
						display.setWidgetAtIndex(new WelcomeHomeWidget(), PlaceConstants.LayoutPosition.CONTENT, -1, false);
					} else if(menuEvent.getMenuItem().equals(MenuItem.ACCOUNT)){
						display.setWidgetAtIndex(new WelcomeAccountWidget(), PlaceConstants.LayoutPosition.CONTENT, -1, false);
					} else if(menuEvent.getMenuItem().equals(MenuItem.OFFICE)){
						display.setWidgetAtIndex(new WelcomeOfficeWidget(), PlaceConstants.LayoutPosition.CONTENT, -1, false);
					} else if(menuEvent.getMenuItem().equals(MenuItem.CUSTOMER)){
						display.setWidgetAtIndex(new WelcomeCustomerWidget(), PlaceConstants.LayoutPosition.CONTENT, -1, false);
					} else if(menuEvent.getMenuItem().equals(MenuItem.TRAINING)){
						display.setWidgetAtIndex(new WelcomeTrainningWidget(), PlaceConstants.LayoutPosition.CONTENT, -1, false);
					}
				}
			}
		}));
	}
    
	private MenuWidget getMenu() {
		if (menu == null) {
			menu = new MenuWidget();
		}
		return menu;
	}
    

	protected void updateToCart(List<ShoppingCartItem> its) {
		eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.MASK));
		for (ShoppingCartItem it : its) {
			
			Order order = null;
			
			for (ShoppingCartItem itm : items) {
				if (itm.getNumber() == it.getNumber()) {
					itm.setQuantity(it.getQuantity());
					
					for (Order or : cart.getOrders()) {
						if(or.getId().equals(itm.getOrderId())){
							order = or;
							order.setQuantity((short) itm.getQuantity());
							break;
						}
					}
					
					break;
				}
			}

			if (order != null) {
				ServiceCatalog.getShoppingService().saveOrUpdateOrder(order,
						new AbstractAsyncCallback<Order>() {

							@Override
							public void onSuccess(Order result) {
								for (Order or : cart.getOrders()) {
									if (or.getId().equals(result.getId())) {
										or.setQuantity(result.getQuantity());
										break;
									}
								}
								eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.UN_MASK));
								GuiUtils.info("Update order to cart successfull!!");
								updateCartPreview();
							}
						});
			}
		}
	}

	protected void removeFromCart(List<ShoppingCartItem> its) {
		eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.MASK));
		final ArrayList<Order> orders = new ArrayList<Order>(items.size());
		for (ShoppingCartItem it : its) {
			int itemsSize = items.size();
			ShoppingCartItem item = null;
			
			for (int i = 0; i < itemsSize; i++) {
				if (items.get(i).getNumber() == it.getNumber()) {
					item = items.remove(i);
					break;
				}
			}
			
			if(item != null){
				Order order = new Order();
				order.setId(item.getOrderId());
				orders.add(order);
			}
		}

		if (!orders.isEmpty()) {
			if (orders.size() == 1) {
				ServiceCatalog.getShoppingService().deleteOrder(orders.get(0),
						new AbstractAsyncCallback<Void>() {

							@Override
							public void onSuccess(Void result) {
								eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.UN_MASK));
								GuiUtils.info("Delete order in cart successfull!!");
								for (Order or : cart.getOrders()) {
									if (or.getId()
											.equals(orders.get(0).getId())) {
										cart.getOrders().remove(or);
										break;
									}
								}
								updateCartPreview();
							}

						});
			} else {
				ServiceCatalog.getShoppingService().deleteOrders(orders,
						new AbstractAsyncCallback<Void>() {

							@Override
							public void onSuccess(Void result) {
								eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.UN_MASK));
								GuiUtils.info("Delete orders in cart successfull!!");
								for (Order order : orders) {
									for (Order or : cart.getOrders()) {
										if (or.getId()
												.equals(order.getId())) {
											cart.getOrders().remove(or);
											break;
										}
									}
								}
								updateCartPreview();
							}
						});
			}
		}
	}


	// Below code will be moved to suitable class
    private Cart cart = null;
    
    public Cart getCart(){
    	return cart;
    }
    
    private void checkOutCart(String paymentType, Long paymentValue){
    	eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.MASK));
    	
    	Payment payment = new Payment();
    	payment.setPaymentType(paymentType);
    	payment.setValue(paymentValue); 
    	
    	ServiceCatalog.getShoppingService().completeCart(cart.getId(), payment,
				new AbstractAsyncCallback<Void>() {

					@Override
					public void onSuccess(Void result) {
						eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.UN_MASK));
						GuiUtils.info("Checkout cart successfull! Please wait to create new cart!");
						createNewCart(true);
					}
				});	
    }
    
    public static int currentCartItemNumber;
    private List<ShoppingCartItem> items;
    
    private void addToCart(List<ShoppingCartItem> its) {
    	eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.MASK));
    	final ArrayList<Order> orders = new ArrayList<Order>(items.size());
    	
    	for (ShoppingCartItem item : its) {
	    	boolean exist = false;
	    	for (ShoppingCartItem it : items) {
				if(it.getNumber() == item.getNumber()){
					it.setQuantity((short) (it.getQuantity() + item.getQuantity()));
					exist = true;
					break;
				}
			}
	    	Order order = null;
	    	if(!exist){
	    		order = createOrderFromShoppingCartItem(item);
	    		order.setCart(cart);
	    	} else {
	    		for (Order or : cart.getOrders()) {
					if(or.getId().equals(item.getOrderId())){
						order = or;
						order.setQuantity((short) item.getQuantity());
						break;
					}
				}
	    	}
	    	
			if (order != null) {
				orders.add(order);
			}
    	}
    	
    	if(!orders.isEmpty()){
    		ServiceCatalog.getShoppingService().saveOrUpdateOrders(orders,
    				new AbstractAsyncCallback<ArrayList<Order>>() {

    					@Override
    					public void onSuccess(ArrayList<Order> result) {
    						updateCartWithOrderFromDB(result);
    					}

    				});	
    	} else {
    		eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.UN_MASK));
    		GuiUtils.alert("No order to update!!");
    	}
    }
    
    private void updateCartWithOrderFromDB(ArrayList<Order> dbOrders){
    	for (Order dbOrder : dbOrders) {
    		boolean exist = false;
			for (Order or : cart.getOrders()) {
				if(or.getId().equals(dbOrder.getId())){
					or.setQuantity(dbOrder.getQuantity());
					exist = true;
					break;
				}
			}
			
			if(!exist){
				cart.getOrders().add(dbOrder);
				items.add(createShoppingCartItemFromOrder(dbOrder));
			}
			
		}
		
		eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.UN_MASK));
		GuiUtils.info("Update order in cart successfull!!");
		updateCartPreview();
    }
    
    private Order createOrderFromShoppingCartItem(ShoppingCartItem item) {
		Order order = new Order();
		
		order.setProduct(item.getProduct());
		order.setQuantity(Short.parseShort(String.valueOf(item.getQuantity())));
		order.setTypeCode("BUY");
		
		return order;
	}
    
    private ShoppingCartItem createShoppingCartItemFromOrder(Order order) {
    	
    	ShoppingCartItem item = new ShoppingCartItem();
		item.setOrderId(order.getId());
		item.setProduct(order.getProduct());
		item.setQuantity(order.getQuantity());
		
		return item;
	}


	private ShoppingCartPreviewWidget cartPreview = null;
	
	private User user;
	
	private void loadCart() {
		eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.MASK));
		ServiceCatalog.getShoppingService().getOpenCartByDistributorId(
				user.getPerson().getDistributor().getId(),
				new AbstractAsyncCallback<Cart>() {

					@Override
					public void onSuccess(Cart result) {
						if (result == null) {
							createNewCart(false);
						} else {
							cart = result;
							eventBus.fireEvent(new RootEvent(
									RootEvent.ForwardType.UN_MASK));
							initShoppingCartItemFromOrders();
						}
					}
				});
	}
	
	private void initShoppingCartItemFromOrders(){
		if(cart.getOrders() != null){
			currentCartItemNumber = cart.getOrders().size();
	    	items = new ArrayList<ShoppingCartItem>(currentCartItemNumber);
	    	
	    	for (Order or : cart.getOrders()) {
	    		items.add(createShoppingCartItemFromOrder(or));
			}
		} else {
			currentCartItemNumber = 0;
	    	items = new ArrayList<ShoppingCartItem>();
	    	cart.setOrders(new ArrayList<Order>());
		}
    	
		loadStoreContext(cart.getId().toString());
	}
	private void createNewCart(final boolean gotoCatalog){
		eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.MASK));
    	ServiceCatalog.getShoppingService().createCart(user.getPerson(),
				new AbstractAsyncCallback<Cart>() {

					@Override
					public void onSuccess(Cart result) {
						eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.UN_MASK));
						cart = result;
						if(gotoCatalog){
							eventBus.fireEvent(new NavigationEvent(NavigationItem.PRODUCT_CATALOG));
						}
						initShoppingCartItemFromOrders();
					}

				});		
	}
	
	private AdvWidget tryalso;
	
	private AdvWidget getWdgTryAlso(){
		if (tryalso == null) {
			tryalso = new AdvWidget();
			
			Image img = new Image("images/product/Kindermins.jpg");
			img.addStyleDependentName("small");
			VerticalPanel tryAlsoContent = new VerticalPanel();
			tryAlsoContent.add(img);
			
			HTML htmPro = new HTML();
			htmPro.setHTML("<center>Kindermins</center>");
			htmPro.setStyleName("productLink");
			tryAlsoContent.add(htmPro);
			
			tryalso.loadData(tryAlsoContent,display.getTextTryAlso());
		}
		return tryalso;
	}
	
	private void loadStoreContext(String cartId) {
		display.setWidgetAtIndex(getWdgCartPreview(cartId), LayoutPosition.CONTEXT, -1,false);
    	display.setWidgetAtIndex(getWdgTryAlso(), LayoutPosition.CONTEXT, 1,false);
	}
	
    private ShoppingCartPreviewWidget getWdgCartPreview(String cartId) {
		if (cartPreview == null) {
			cartPreview = new ShoppingCartPreviewWidget();
		}
		
		cartPreview.loadData(createCartPreviewObject());
		cartPreview.setClosed(false);
		cartPreview.setCartId(cartId);
		
		return cartPreview;
    }
	
	private void updateCartPreview(){
		if (cartPreview != null) {
			cartPreview.loadData(createCartPreviewObject());
		}
	}
	
	private ShoppingCartPreviewObject createCartPreviewObject(){
		ShoppingCartPreviewObject result = new ShoppingCartPreviewObject();
		int point = 0;
		
		if(items != null && !items.isEmpty()){
			ShoppingCartPreviewItem cartItem = null;
			result.setItems(new ArrayList<ShoppingCartPreviewItem>(items.size()));
			
			for (ShoppingCartItem it : items) {
				cartItem = new ShoppingCartPreviewItem();
				cartItem.setName(it.getProduct().getName());
				cartItem.setQuantity(it.getQuantity());
				
				point += it.getProduct().getVolumePoint()
				* it.getQuantity();
				
				result.getItems().add(cartItem);
			}
		}
		
		Date date = new Date();
		
		MonthlyPoint monthlyPoint = GuiUtils.getCurrentMonthlyPoint(user.getPerson().getDistributor().getMonthlyPoints());
		
		result.setDiscountScale(user.getPerson().getDistributor().getLevel().getDiscountScale());
		result.setMonthlyPoint(monthlyPoint);
		result.setOrderMonth(GuiUtils.format(date, GuiUtils.MM_YYYY));
		result.setPoint(point);
		
		return result;
	}
	
    @Override
    public Place getPlace() {
        return PLACE;
    }

    private void setWidgetPresenter(final WidgetPresenter<?> p, LayoutPosition position) {
    	display.setWidgetAtIndex(p.getDisplay().asWidget(), position, 0, false);
    }
    
	public List<ShoppingCartItem> getItems() {
		return items;
	}
	
	public String getDistributorCode() {
		String result = user.getPerson().getDistributor().getCode();
		return result;
	}
	
	public String getFullName() {
		String result = user.getPerson().getFirstName() + " "
				+ user.getPerson().getLastName();
		return result;
	}
	
	public User getUser() {
		return user;
	}
	
	private DialogBox loadingBox;
	
	private boolean loading = false;
	
	public void mask() {
		if (!loading) {
			display.visibleContent(false);
			getLoadingBox().center();
			getLoadingBox().show();
			loading = true;
		}
	}

	public void unmask() {
		if (loading) {
			display.visibleContent(true);
			getLoadingBox().hide();
			loading = false;
		}
	}
	
	private DialogBox getLoadingBox() {
		if(loadingBox == null){
			loadingBox = new DialogBox();
			loadingBox.setGlassEnabled(true);
			loadingBox.setStyleName("gwt-DialogLoading");
			loadingBox.setAnimationEnabled(true);
		    Image image = new Image("images/icons/ico_loading.gif");
		    image.setSize("135px", "100px");
			loadingBox.setWidget(image);
		}
	    // Return the dialog box
	    return loadingBox;
	  }

	public LoginFormWidget getLoginFormWidget() {
		if(loginFormWidget == null){
			loginFormWidget = new LoginFormWidget();
		}
		return loginFormWidget;
	}

	public LoginInfoWidget getLoginInforWidget() {
		if(loginInforWidget == null){
			loginInforWidget = new LoginInfoWidget();
		}
		return loginInforWidget;
	}
}
